package org.mindrive.system.service.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.tika.Tika;
import org.mindrive.system.collection.system.FileEntity;
import org.mindrive.system.collection.system.UserEntity;
import org.mindrive.system.service.BaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * (File)表服务接口
 *
 * @author maweihong
 * @since 2023-10-11 17:16:02
 */
@Service
@Slf4j
public class FileService extends BaseService {

    @Value("${file.path}")
    private String filesUploadPath;//获取文件路径

    public String download(String fileId, HttpServletResponse response) {
        InputStream inputStream = null;
        File file = null;
        String fileName = "";
        try {
            QueryWrapper<FileEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", fileId);
            FileEntity filesE= fileDao.getOne(queryWrapper,false);

//            getFileFromBase64String(filesE.getFileContent() , filesUploadPath + "//" + filesE.getFileUuid());

            file = new File(filesUploadPath + "//" + filesE.getFileUuid());
            FileEntity comparisonFileManagementEntitie = fileDao.getOne(new QueryWrapper<FileEntity>().eq("FILE_UUID", filesE.getFileUuid()));
            fileName = comparisonFileManagementEntitie.getUserFileName();
            Tika tika = new Tika();
            String contentType = tika.detect(file);
            inputStream = new FileInputStream(file);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int b = 0;
            while ((b = inputStream.read()) != -1) {
                os.write(b);
            }

            // 设置response返回头部信息
            response.setHeader("content-type", contentType);
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("X-Frame-Options", "SAMEORIGIN");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setContentLength(os.size());
            response.getOutputStream().write(os.toByteArray());


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    inputStream = null;
                }
            }
        }
        return fileName;
    }

    public static String getBase64StringFromFile(File file) {
        String result = "";
        try {
            InputStream is = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int ch ;
            while((ch = is.read()) != -1)   {
                baos.write(ch);
            }
            byte[] bs = baos.toByteArray();
            result = Base64.encodeBase64String(bs);
            is.close();
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static boolean getFileFromBase64String(String base64Str , String filePath) {
        byte[] bs = Base64.decodeBase64(base64Str);
        FileOutputStream fos = null;
        try {
            File f = new File(filePath);
            if(!f.exists())
                f.createNewFile();
            fos = new FileOutputStream(f);
            fos.write(bs);
            fos.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;

    }

}

